/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "ohos_window.h"
#include <stdio.h>
#include <native_window/external_window.h>
#include <native_buffer/native_buffer.h>
#include <native_window/graphic_error_code.h>
#include <EGL/egl.h>
#include "ohos_log.h"

OH_NativeBuffer_Format EglFormatToNativeFormat(EGLint eglFormat)
{
    return static_cast<OH_NativeBuffer_Format>(eglFormat);
}

int ANativeWindow_setBuffersGeometry(ANativeWindow *window, int width, int height, EGLint format)
{
    OHNativeWindow *nativeWindow = static_cast<ANativeWindow *>(window);
    if (nativeWindow == nullptr) {
        return NATIVE_ERROR_NOT_INIT;
    }
    int ret = 0;

    if ((ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, SET_BUFFER_GEOMETRY, width, height)) != 0) {
        return ret;
    }

    if ((ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, SET_FORMAT, EglFormatToNativeFormat(format))) != 0) {
        return ret;
    }
    return ret;
}

void ANativeWindow_release(ANativeWindow *window)
{
    OHNativeWindow *nativeWindow = static_cast<ANativeWindow *>(window);
    if (nativeWindow == nullptr) {
        return;
    }
    OH_NativeWindow_NativeObjectUnreference(nativeWindow);
}

int ANativeWindow_getWidth(ANativeWindow *window)
{
    OHNativeWindow *nativeWindow = static_cast<ANativeWindow *>(window);
    if (nativeWindow == nullptr) {
        LOGE("native window is nullptr");
        return 0;
    }
    int stride;
    int height;
    if ((OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, GET_BUFFER_GEOMETRY, &height, &stride)) != 0) {
        return 0;
    }
    return stride;
}

int ANativeWindow_getHeight(ANativeWindow *window)
{
    OHNativeWindow *nativeWindow = static_cast<ANativeWindow *>(window);
    if (nativeWindow == nullptr) {
        LOGE("native window is nullptr");
        return 0;
    }
    int stride;
    int height;
    if ((OH_NativeWindow_NativeWindowHandleOpt(nativeWindow, GET_BUFFER_GEOMETRY, &height, &stride)) != 0) {
        return 0;
    }
    return height;
}
